package gmysql

import (
	"fmt"
	"time"

	_ "github.com/go-sql-driver/mysql" // mysql driver
	"github.com/jmoiron/sqlx"

	"bbtradeByGo/pkg/config"
	"bbtradeByGo/pkg/email"
	"bbtradeByGo/pkg/logging"
)

var (

	// DB 本服务数据库连接
	DB *sqlx.DB
)

// 映射数据对象属性名到字段名方法
func mapper(name string) string {
	var s []byte
	for i, r := range []byte(name) {
		if r >= 'A' && r <= 'Z' {
			r += 'a' - 'A'
			if i != 0 {
				s = append(s, '_')
			}
		}
		s = append(s, r)
	}
	return string(s)
}

// Connect 初始化数据库连接池
func Connect(driver, uri string, maxOpen, maxIdel int) (db *sqlx.DB, err error) {

	db, err = sqlx.Connect(driver, uri+"?charset=utf8mb4&parseTime=true")
	if err != nil {
		return
	}
	// 配置连接池
	db.SetMaxOpenConns(maxOpen)
	db.SetMaxIdleConns(maxIdel)
	db.SetConnMaxLifetime(2 * time.Hour)
	// ping
	// db.Ping()
	// defer DB.Close()
	return
}


// Setup 初始化本服务数据库
func Setup() (err error) {
	// URL database url
	URL := fmt.Sprintf("%s:%s@(%s)/%s",
		config.DatabaseSetting.User,
		config.DatabaseSetting.Password,
		config.DatabaseSetting.Host,
		config.DatabaseSetting.Name)
	
	fmt.Println("url----->", URL)
	DB, err = Connect("mysql", URL, 500, 500)
	if err != nil {
		logging.Error("pkg.gmysql.Setup", err)
		email.SendMail("pkg.gmysql.Setup", err.Error())
		return err
	}
	DB.MapperFunc(mapper)

	sqlx.NameMapper = mapper // sqlx.Named 使用的mapper方法
	return
}
